package se.thoka.twt.client.widgets;

import java.util.NoSuchElementException;

import se.thoka.twt.client.utils.DOMUtil;

import com.google.gwt.dom.client.Element;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public class TWTPanel extends HTMLPanel {

	/**
	 * Creates an HTML panel with the specified HTML contents inside a DIV
	 * element. Any element within this HTML that has a specified id can contain
	 * a child widget.
	 * 
	 * @param html
	 *            the panel's HTML
	 */
	public TWTPanel(String html) {
		super(html);
	}

	/**
	 * Initializes the panel's HTML from a given {@link SafeHtml} object.
	 * 
	 * Similar to {@link #HTMLPanel(String)}
	 * 
	 * @param safeHtml
	 *            the html to set.
	 */
	public TWTPanel(SafeHtml safeHtml) {
		super(safeHtml);
	}

	/**
	 * Creates an HTML panel whose root element has the given tag, and with the
	 * specified HTML contents. Any element within this HTML that has a
	 * specified id can contain a child widget.
	 * 
	 * @param tag
	 *            the tag of the root element
	 * @param html
	 *            the panel's HTML
	 */
	public TWTPanel(String tag, String html) {
		super(tag, html);
	}
	
	@Override
	public void add(Widget widget, String id) {
		try {
			super.add(widget, id);
		} catch (NoSuchElementException e) {
			// Ignore
		}
	}
	
	@Override
	public void add(Widget child, Element container) {
	    com.google.gwt.user.client.Element containerElem = container.cast();
	    // Detach new child.
	    child.removeFromParent();

	    // Logical attach.
	    getChildren().add(child);

	    // Physical attach.
	    DOM.appendChild(containerElem, child.getElement());

	    // Adopt.
	    adopt(child);
	}
	
	@SuppressWarnings("deprecation")
	public void addAndReplaceElement(IsWidget widget, com.google.gwt.user.client.Element toReplace) {
		super.addAndReplaceElement(widget.asWidget(), toReplace);
	}
	
	@Override
	public void addAndReplaceElement(Widget widget, String id) {
		try {
			super.addAndReplaceElement(widget, id);
		} catch (NoSuchElementException e) {
			// Ignore.
		}
	}
	
	@Override
	public com.google.gwt.user.client.Element getElementById(String id) {
		return DOMUtil.getChildById(getElement(), id);
	}
}
